from fastapi import APIRouter, Query

from fastapiApp.controllers.role_control import role_controller
from fastapiApp.schemas.base_scheams import Success, SuccessExtra ,Fail
from fastapiApp.schemas.role_schemas import *

router = APIRouter()

@router.get("/get_list", summary="查看角色列表")
async def list_role(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    role_name: str = Query("", description="角色名称，用于查询")
):
    total,data = await role_controller.list(page=page, page_size=page_size, role_name=role_name)
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@router.get("/get_info", summary="查看角色")
async def get_role(
    role_id: int = Query(..., description="角色ID")
):
    role_obj = await role_controller.model.get(id=role_id)
    data = await role_obj.to_dict()
    return Success(data=data)

@router.post("/create", summary="创建角色")
async def create_role(role_in: RoleCreate):
    await role_controller.is_exist(obj_in = role_in)
    await role_controller.model.create(** role_in.model_dump())
    return Success(msg="Created Successfully")

# // 错误接口
@router.post("/update", summary="更新角色")
async def update_role(obj_in: RoleUpdate):
    await role_controller.update(id=obj_in.id, obj_in=obj_in)
    return Success(msg=f"Update Successfully By ID = {obj_in.id}")
#
#

@router.delete("/delete", summary="删除角色")
async def delete_role(
    id: int = Query(..., description="角色ID")
):
    role = await role_controller.model.get_or_none(id = id)
    if role:
        await role.delete()
        return Success(msg=f"Deleted Success By ID = {id}")
    else:
        return Fail(msg=f"ID {id} 不存在")

@router.get("/authorized", summary="查看角色权限")
async def get_role_authorized(id: int = Query(..., description="角色ID")):
    role_obj = await role_controller.get(id=id)
    data = await role_obj.to_dict(m2m=True)
    return Success(data=data)

@router.post("/authorized", summary="更新角色权限")
async def update_role_authorized(role_in: RoleUpdateMenusApis):
    role_obj = await role_controller.get(id=role_in.id)
    await role_controller.update_roles(role=role_obj, menu_ids=role_in.menu_ids, api_infos=role_in.api_infos)
    return Success(msg="Updated Successfully")
